<template>
  <div class="app-container"
       v-wechat-title="'博文列表'">
    <el-card class="box-card">
      <!-- 查询搜索和其他操作-->
      <el-form ref="queryForm" :inline="true" :model="queryParams" label-width="68px" size="small">
        <el-form-item>
          <el-button
              icon="el-icon-plus"
              type="success"
              @click="$router.push('blog-add-or-update')"
              :disabled="isAuth('sys:blog:add')"
          >新增
          </el-button>
          <el-autocomplete
              clearable
              style="width: 150px;margin-left: 10px"
              class="inline-input"
              v-model="queryParams.title"
              :fetch-suggestions="querySuggest"
              placeholder="博文标题"
              :trigger-on-focus="false"
              @keyup.enter.native="handleQuery()"
          ></el-autocomplete>
          <el-select
              v-model="queryParams.isRelease"
              style="width: 110px;margin-left: 5px"
              filterable
              clearable
              placeholder="发布状态">
            <el-option
                v-for="(item,index) in releaseParams"
                :key="index"
                :label="item"
                :value="index">
            </el-option>
          </el-select>
          <!--          <el-select-->
          <!--              v-model="queryParams.isTop"-->
          <!--              style="width: 110px;margin-left: 5px"-->
          <!--              filterable-->
          <!--              clearable-->
          <!--              placeholder="置顶">-->
          <!--            <el-option-->
          <!--                v-for="(item,index) in topParams"-->
          <!--                :key="index"-->
          <!--                :label="item"-->
          <!--                :value="index">-->
          <!--            </el-option>-->
          <!--          </el-select>-->
          <el-select
              v-model="queryParams.isComment"
              style="width: 110px;margin-left: 5px"
              filterable
              clearable
              placeholder="评论状态">
            <el-option
                v-for="(item,index) in commentParams"
                :key="index"
                :label="item"
                :value="index">
            </el-option>
          </el-select>
          <el-select
              v-model="queryParams.categoryId"
              style="width: 110px;margin-left: 5px"
              filterable
              clearable
              placeholder="分类名">
            <el-option
                v-for="item in categories"
                :key="item.id"
                :label="item.name"
                :value="item.id">
            </el-option>
          </el-select>
          <el-select
              v-model="tagIds"
              style="width: 180px;margin-left: 5px"
              multiple
              filterable
              clearable
              placeholder="标签名">
            <el-option
                v-for="item in tags"
                :key="item.id"
                :label="item.name"
                :value="item.id">
            </el-option>
          </el-select>
          <el-date-picker
              v-model="time"
              style="margin-left: 5px;max-width: 385px"
              type="datetimerange"
              :picker-options="pickerOptions"
              value-format="yyyy-MM-dd HH:mm:ss"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              align="right">
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button style="margin-left: 5px" icon="el-icon-search" type="primary"
                     @click="handleQuery()">搜索
          </el-button>
          <el-button style="margin-left: 12px" icon="el-icon-refresh" @click="handleReset">重置</el-button>

          <el-button type="danger" @click="handleDelete()" :disabled="multiple || isAuth('sys:blog:delete')"
                     style="margin-left: 12px" icon="el-icon-delete">删除
          </el-button>
          <el-button class="filter-item" type="warning" :disabled="multiple || isAuth('sys:blog:export')"
                     @click="handleDownload" icon="el-icon-download">导出
          </el-button>
        </el-form-item>
      </el-form>

      <!-- 表格-->
      <el-table
          v-loading="loading"
          :data="blogsData"
          style="width: 100%"
          border
          @selection-change="handleSelectionChange">
        <el-table-column
            type="selection"
            width="55">
        </el-table-column>

        <!--        <el-table-column-->
        <!--            type="index"-->
        <!--            label="编号"-->
        <!--            width="55">-->
        <!--        </el-table-column>-->
        <el-table-column
            label="发布状态"
            width="100">
          <template slot-scope="scope">
            <el-tag :type="scope.row.isRelease == 0 ? 'warning' : 'success'">
              {{ scope.row.isRelease == 1 ? '已发布' : '未发布' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
            label="标题"
            width="250">
          <template slot-scope="scope">
            {{ scope.row.title }}
          </template>
        </el-table-column>

        <el-table-column
            width="80"
            prop="author"
            label="作者">
        </el-table-column>

        <el-table-column
            align="center"
            width="120"
            prop="categoryName"
            label="分类">
        </el-table-column>

        <el-table-column label="标签" width="280" align="center">
          <template slot-scope="scope">
            <div style="display: inline-block;margin-left: 5px" v-for="(item,index) in scope.row.tagsName"
                 :key="index">
              <el-tag type="danger">{{ item }}</el-tag>
            </div>
          </template>
        </el-table-column>

        <el-table-column
            width="80"
            prop="commentCount"
            label="评论量">
        </el-table-column>

        <el-table-column
            width="80"
            prop="clickNum"
            label="点击次数">
        </el-table-column>

        <el-table-column
            label="创建时间"
            width="155">
          <template slot-scope="scope">{{ scope.row.createTime }}</template>
        </el-table-column>

        <el-table-column
            label="修改时间"
            width="155">
          <template slot-scope="scope">{{ scope.row.modifiedTime == null ? '暂无修改' : scope.row.modifiedTime }}</template>
        </el-table-column>

        <el-table-column label="操作" width="180">
          <template slot-scope="scope">
            <el-tooltip class="item" effect="dark" content="设置文章" placement="top">
              <el-button style="background: #ffe7da"
                         icon="el-icon-s-tools"
                         circle
                         @click="handleSetting(scope.row.id)"></el-button>
            </el-tooltip>
            <el-tooltip class="item" effect="dark" content="修改文章信息" placement="top">
              <el-button
                  type="info"
                  icon="el-icon-edit-outline"
                  circle
                  :disabled="isAuth('sys:blog:update')"
                  @click="handleUpdate(scope.row.id)">
              </el-button>
            </el-tooltip>
            <el-tooltip class="item" effect="dark" content="删除该文章" placement="top">
              <el-button type="danger"
                         icon="el-icon-delete"
                         circle
                         :disabled="isAuth('sys:blog:delete')"
                         @click="handleDelete(scope.row.id)"></el-button>
            </el-tooltip>

          </template>
        </el-table-column>
      </el-table>

      <!-- 分页-->
      <pagination
          v-show="pagination.total>0"
          :total="pagination.total"
          :page.sync="pagination.currentPage"
          :limit.sync="pagination.pageSize"
          @pagination="handleQuery"
      />

      <!--  博文设置    -->
      <el-dialog
          title="博文设置"
          :visible.sync="blogSettingDialog"
          width="30%"
          center>
        <el-form :model="blogSettingForm" label-width="80px">
          <el-form-item label="置顶博文:">
            <el-switch v-model="blogSettingForm.isTop"></el-switch>
          </el-form-item>
          <el-form-item label="评论开关:">
            <el-switch v-model="blogSettingForm.isComment"></el-switch>
          </el-form-item>
          <el-form-item label="发布状态:">
            <el-radio-group v-model="blogSettingForm.isRelease">
              <el-radio label="0">下架中</el-radio>
              <el-radio label="1">发布中</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="blogSettingDialog = false">取 消</el-button>
          <el-button type="primary" @click="submitSetting()">确 定</el-button>
        </div>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>

import {page, delBlog, getSuggest, detail, settingBlog} from '@/api/blog'
import {categoryList} from '@/api/category'
import {tagList} from '@/api/tag'

export default {
  name: "blog",
  components: {},
  data() {
    return {
      loading: true,
      time: [],
      queryParams: {
        title: undefined,       //标题搜索
        isRelease: undefined,       //状态搜索
        categoryId: undefined,    //分类搜索
        tagIds: undefined,       //标签搜索
      },
      pagination: {
        currentPage: 1,
        pageSize: 10,
        total: 0
      },
      // 非多个禁用
      multiple: true,
      blogsData: [],
      ids: [],
      categories: [],
      tags: [],
      tagIds: [],
      releaseParams: ['未发布', '已发布'],
      topParams: ['置顶', '未置顶'],
      commentParams: ['关闭', '开启'],
      download: [],
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
      blogSettingDialog: false,
      blogSettingForm: {
        id: '',
        isComment: false,
        isTop: false,
        isRelease: '0'
      },
    }
  },

  methods: {
    //获取博客列表
    handleQuery() {
      if (this.time) {
        this.queryParams.startTime = this.time[0]
        this.queryParams.endTime = this.time[1]
      } else {
        this.queryParams.startTime = ''
        this.queryParams.endTime = ''
      }
      this.loading = true;
      this.queryParams.currentPage = this.pagination.currentPage
      this.queryParams.pageSize = this.pagination.pageSize
      let tagId = this.tagIds.length > 0 ? this.tagIds.join(",") : undefined
      this.queryParams.tagIds = tagId
      page(this.queryParams).then(res => {
        this.blogsData = res.data.records
        this.pagination.currentPage = res.data.current
        this.pagination.pageSize = res.data.size
        this.pagination.total = res.data.total
        this.loading = false
      })
    },
    //获取查询建议
    querySuggest(queryString, cb) {
      let trim = queryString.trim();
      getSuggest(trim).then(res => {
        // 调用 callback 返回建议列表的数据
        cb(res.data)
      })
    },
    //修改博文
    handleUpdate(id) {
      this.$router.push({path: 'blog-add-or-update', query: {bId: id}})
    },

    //复选框
    handleSelectionChange(selection) {
      this.download = []
      this.download = selection
      this.ids = selection.map(item => item.id)
      this.multiple = !selection.length
    },

    //删除博文
    handleDelete(id) {
      let delIds = id ? id : this.ids
      this.$confirm(`是否删除编号:${delIds}的博文`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delBlog(delIds).then(() => {
          setTimeout(() => {
            this.handleQuery()
            this.$message.success('删除成功!')
          }, 1000);
        })
      }).catch(() => {
      });
    },
    //导出选中的文章
    handleDownload() {
      this.$confirm(`是否导出选中的博文`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.download.forEach(item => {
          this.downFile(item.title, item.content)
        })
      }).catch(() => {
      });
    },

    /**
     * 下载文件
     * @param title：标题
     * @param text：正文
     */
    downFile: (title, text) => {
      title = title || "默认标题"

      //创建一个blob对象,file的一种
      let blob = new Blob([text])

      let link = document.createElement('a')

      link.href = window.URL.createObjectURL(blob)

      //配置下载的文件名
      link.download = title + '.md'

      link.click()
    },

    //重置
    handleReset() {
      this.pagination = {
        currentPage: 1,
        pageSize: 10,
        total: 0
      }
      this.queryParams = {
        title: undefined,
        isRelease: undefined,
        categoryId: undefined,
        tagIds: undefined,
      }
      this.tagIds = []
      this.time = []
      this.handleQuery()
    },
    //打开博文设置
    handleSetting(blogId) {
      detail(blogId).then(res => {
        if (res.status) {
          const blog = res.data
          this.blogSettingForm.id = blog.id
          this.blogSettingForm.isTop = blog.isTop === 1 ? true : false
          this.blogSettingForm.isComment = blog.isComment === 1 ? true : false
          this.blogSettingForm.isRelease = blog.isRelease + ''
        }
      }).then(() => {
        this.blogSettingDialog = true
      })
    },
    //提交博文设置
    submitSetting() {
      let form = {
        'id': this.blogSettingForm.id,
        'isTop': this.blogSettingForm.isTop ? 1 : 0,
        'isComment': this.blogSettingForm.isComment ? 1 : 0,
        'isRelease': this.blogSettingForm.isRelease
      }
      settingBlog(form).then(res => {
        if (res.status) {
          this.$message.success('修改成功')
          this.blogSettingDialog = false
        }
      })
    }
  },

  created() {
    this.handleQuery()
    categoryList().then(res => {
      this.categories = res.data
    }).then(() => {
      let tempCategory = this.$route.query.category;
      //首页跳转-搜索指定分类
      if (tempCategory) {
        let filter = this.categories.filter(item => item.name == tempCategory);
        this.queryParams.categoryId = filter[0].id
        this.handleQuery()
      }
    })
    tagList().then(res => {
      this.tags = res.data
    }).then(() => {
      //首页
      let tempLabel = this.$route.query.label;
      //首页跳转-搜索指定标签
      if (tempLabel) {
        let filter = this.tags.filter(item => item.name == tempLabel);
        this.tagIds.push(filter[0].id)
        this.handleQuery()
      }
    })

  }
}
</script>

<style scoped>
.box-card {
  height: 100%;
}

.inputSearch {
  width: 300px;
}

.searchRow {
  margin-top: 20px;
}

.pageSize {
  margin-top: 20px;
  text-align: center;
}

.dialog {
  overflow-x: hidden;
}
</style>
